import axios from 'axios'
import router from '@/router'
import store from '@/store'

axios.defaults.withCredentials = true;

//过滤请求
axios.interceptors.request.use( function (config) {
  config.timeout = 7200 * 1000 //请求响应时间
  return config
},   function (error) {
  return Promise.reject(error)
})

// 全局请求拦截器
axios.interceptors.response.use(function (response) {
  // console.log(response.data)
  if (response.data.code == 11000 || (response.data.message && (response.data.message.includes('无权操作') || response.data.message.includes('未登录') || response.data.message.includes('登录已超时') || response.data.message.includes('登录信息失效')))){
    store.commit("changeMenuList",[]);
    store.commit("addUser",{});
    router.push({
      path:"/singleError",
      query:{
        ssoError:response.data.message
      }
    });
    return
  }
  return response
},
  error => {
    // console.log(error.response)
    if (error && error.response) {
      if(error.response.status == 404){
        router.push({
          path:"/singleError",
          query:{
            ssoError: "访问接口地址错误（404）",
            code: 404
          }
        });
      } else if(error.response.status == 500){
        router.push({
          path:"/singleError",
          query:{
            ssoError: "请求错误(500)",
            code: 500
          }
        });
        return
      } else {
        router.push({
          path:"/singleError",
          query:{
            ssoError: `请求错误(${error.response.status})`,
            code: error.response.status
          }
        });
        return
      }
    } else {
      router.push({
        path:"/singleError",
        query:{
          ssoError: "请求超时，服务器无响应",
          code: 0
        }
      });
      return
    }
  })

export default  function request(method, url, data) { //暴露 request 给我们好API 管理
  method = method.toLocaleLowerCase() //封装RESTful API的各种请求方式 以 post get delete为例
  if (method === 'post') {
    return  axios.post(url, data) //axios的post 默认转化为json格式
  } else if (method === 'get') {
    return  axios.get(url, {
      params: data
    })
  } else if (method === 'delete') {
    return  axios.delete(url, {
      params: data
    })
  }
}
